package com.springcloud.auth.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static io.jsonwebtoken.SignatureAlgorithm.*;

/**
 * @version V1.0
 * @Author 宋聚智
 * @Date 2019/11/5 8:59
 * @description
 * @Modify By：
 * @ModifyTime： 2019/11/5
 * @Modify marker：
 **/
public class JWTUtil {
    public static final String SECRET_KEY = "123456";//密钥
    public static final long TOKEN_EXPRSE_TIME = 5 * 6 * 1000;
    public static final long REFRESH_TOKEN_EXPIRE_TIME = 10 * 6 * 1000;//refreshToken 过期时间
    private static final String ISSUER = "issuer";

    public static String BASE64_SECRET_KEY;
    static {
        BASE64_SECRET_KEY=Base64.getEncoder().encodeToString(SECRET_KEY.getBytes(StandardCharsets.UTF_8));
    }
    //生成签名
    public static String generateToken(String username){

        Map<String,Object> claims= new HashMap<>();
        claims.put("username",username);
        Date now= new Date();
        ZoneId zone=ZoneId.systemDefault();
        String token= Jwts.builder().setIssuer(ISSUER).setIssuedAt(now).setExpiration(new Date(now.getTime()+TOKEN_EXPRSE_TIME))
                .setClaims(claims).signWith(HS512,SECRET_KEY).compact();
        return token;
    }

    //验证签名
    public static boolean verify(String token){
        Claims body = Jwts.parser().setSigningKey(Base64.getDecoder()
                .decode(BASE64_SECRET_KEY)).parseClaimsJws(token).getBody();
     return true;

    }

    public static String generateRefreshToken(){
        return UUID.randomUUID().toString().replace("-","");
    }
    public static String getUsername(String token){
        Claims body = Jwts.parser().setSigningKey(Base64.getDecoder().decode(BASE64_SECRET_KEY)).parseClaimsJws(token).getBody();
        Object username = body.get("username");

        return String.valueOf(username);
    }



}
